package com.company.cloud.page.modules.mgr.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseParam;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.tree.CloudTree;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.page.modules.base.entity.PageConfigInfo;
import com.company.cloud.page.modules.base.entity.PageStaticInfo;
import com.company.cloud.page.modules.base.service.PageStaticInfoService;
import com.company.cloud.page.modules.cache.models.PageInfoModel;
import com.company.cloud.page.modules.cache.models.PageStaticModel;
import com.company.cloud.page.modules.cache.models.WebPageConfigModel;
import com.company.cloud.page.modules.cache.utils.PageConvertUtils;
import com.company.cloud.page.modules.mgr.controller.req.*;
import com.company.cloud.product.modules.api.response.ProductCategoryModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 静态页面管理
 */
@Authc
@RestController
@RequestMapping("/mgr/cms/staticPage")
@Api(tags = "Page_MGR_静态页面管理")
public class PageStaticMgrController {


    @Autowired
    private PageStaticInfoService pageStaticInfoService;


    @PostMapping("/tree")
    @ApiOperation(value = "静态页面树", response = PageStaticModel.class)
    public BaseResult tree(@RequestBody PageStaticTreeParam params) {
        List<PageStaticInfo> list = pageStaticInfoService.list(new QueryWrapper<PageStaticInfo>()
                .select("page_no","type","name","share_title","orders","state","parent_page_no")
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .eq(StrUtil.isNotEmpty(params.getType()),"type",params.getType())
                .orderByDesc("orders")
        );
        if(CollUtil.isEmpty(list)){
            return BaseResult.ok();
        }

        CloudTree<PageStaticInfo, PageStaticModel> tree=new CloudTree<PageStaticInfo, PageStaticModel>() {
            @Override
            public boolean isTop(PageStaticModel entity) {
                if(StrUtil.isEmpty(entity.getParentPageNo()) || "0".equals(entity.getParentPageNo())) {
                    return true;
                }else {
                    return false;
                }
            }
            @Override
            public boolean isParent(PageStaticModel parentObj, PageStaticModel childObj) {
                if(parentObj.getPageNo().equals(childObj.getParentPageNo())){
                    return true;
                }else{
                    return false;
                }
            }
            @Override
            public PageStaticModel convert(PageStaticInfo entity) {
                return PageConvertUtils.getPageStaticModel(entity);
            }
        };
        return BaseResult.ok(tree.tree(list));
    }



    @GetMapping("/get")
    @ApiOperation(value="详情",response = PageStaticModel.class)
    public BaseResult get(@RequestParam("pageNo")String pageNo) {
        PageStaticInfo entity= pageStaticInfoService.getById(pageNo);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())){
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        PageStaticModel data= PageConvertUtils.getPageStaticModel(entity);
        return BaseResult.ok(data);
    }



    @PostMapping("/save")
    @ApiOperation(value="新增",response = BaseResult.class)
    public BaseResult save(@RequestBody PageStaticAdd2EditParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();

        PageStaticInfo entity=new PageStaticInfo();

        if(StrUtil.isEmpty(params.getPageNo())){
            entity.setPageNo(StrUtil.format("PS{}", IdUtil.getSnowflake(1,1).nextIdStr()));
        }else{
            entity.setPageNo(params.getPageNo());
        }
        entity.setType(params.getType());
        entity.setName(params.getName());
        entity.setContent(params.getContent());
        entity.setLinkUrl(params.getLinkUrl());
        entity.setShareStyle(params.getShareStyle());
        entity.setShareTitle(params.getShareTitle());
        entity.setShareMemo(params.getShareMemo());
        entity.setShareImg(params.getShareImg());
        entity.setMetaKeywords(params.getMetaKeywords());
        entity.setMetaDescription(params.getMetaDescription());
        entity.setOrders(params.getOrders());
        if(StrUtil.isEmpty(params.getState())){
            entity.setState(BaseConstant.YNEnum.NO.getCode());
        }else{
            entity.setState(params.getState());
        }

        entity.setParentPageNo(params.getParentPageNo());
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        pageStaticInfoService.save(entity);

        return BaseResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation(value="修改",response = BaseResult.class)
    public BaseResult update(@RequestBody PageStaticAdd2EditParam params) {
        ValidatorUtils.validate(params);
        if(StrUtil.isEmpty(params.getPageNo())){
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        PageStaticInfo entity= pageStaticInfoService.getById(params.getPageNo());
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())){
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        if(BaseConstant.YNEnum.YES.getCode().equals(entity.getState())){
            throw new BusinessException(BaseReturnEnum.PARAM_ERROR.getCode(),"发布状态不能修改");
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setType(params.getType());
        entity.setName(params.getName());
        entity.setContent(params.getContent());
        entity.setLinkUrl(params.getLinkUrl());
        entity.setShareStyle(params.getShareStyle());
        entity.setShareTitle(params.getShareTitle());
        entity.setShareMemo(params.getShareMemo());
        entity.setShareImg(params.getShareImg());
        entity.setMetaKeywords(params.getMetaKeywords());
        entity.setMetaDescription(params.getMetaDescription());
        entity.setOrders(params.getOrders());
        entity.setParentPageNo(params.getParentPageNo());
        entity.addEditParam(userInfo);
        pageStaticInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @PostMapping("/updateState")
    @ApiOperation(value="修改状态",response = BaseResult.class)
    public BaseResult updateState(@RequestBody PageStaticStateEditParam params) {
        ValidatorUtils.validate(params);
        PageStaticInfo entity= pageStaticInfoService.getById(params.getPageNo());
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())){
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if(params.getState().equals(entity.getState())){
            return BaseResult.ok();
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setState(params.getState());
        entity.addEditParam(userInfo);
        pageStaticInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @GetMapping("/delete")
    @ApiOperation(value="删除",response = BaseResult.class)
    public BaseResult delete(@RequestParam("pageNo")String pageNo) {
        if(StrUtil.isEmpty(pageNo)){
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        PageStaticInfo entity= pageStaticInfoService.getById(pageNo);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())){
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        int num= pageStaticInfoService.count(new QueryWrapper<PageStaticInfo>()
            .eq("parent_page_no",pageNo)
        );
        if(num>0){
            throw new BusinessException(BaseReturnEnum.PARAM_ERROR.getCode(),"有子节点，不能操作");
        }
        pageStaticInfoService.removeById(pageNo);
        return BaseResult.ok();
    }







}
